package com.example.music.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.music.MainActivity
import com.example.music.MusicDetailActivity
import com.example.music.R
import com.example.music.adapter.PlaylistAdapter
import com.example.music.model.Song
import com.example.music.network.MusicApi
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit

class PlaylistFragment : Fragment() {
    private lateinit var musicApi: MusicApi
    private lateinit var playlistAdapter: PlaylistAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_playlist, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupAdapter(view)
        setupRetrofit()
        
        // 延迟加载数据，确保 Activity 已经完全初始化
        view.post {
            loadData()
        }
    }

    private fun setupAdapter(view: View) {
        playlistAdapter = PlaylistAdapter().apply {
            setOnItemClickListener { playlist, position, playlists ->
                val songs = playlists.map { pl ->
                    Song(
                        id = pl.id,
                        name = pl.name,
                        artist = pl.artist?.takeIf { it.isNotBlank() },
                        coverUrl = pl.coverUrl,
                        url = pl.url
                    )
                }
                startMusicDetail(position, songs)
            }
        }
        view.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.playlistsRecyclerView).apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = playlistAdapter
        }
    }

    private fun setupRetrofit() {
        val client = OkHttpClient.Builder()
            .addInterceptor(HttpLoggingInterceptor().apply { 
                level = HttpLoggingInterceptor.Level.BASIC 
            })
            .connectTimeout(15, TimeUnit.SECONDS)
            .build()

        musicApi = Retrofit.Builder()
            .baseUrl("http://121.37.40.55:3000/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(MusicApi::class.java)
    }

    private fun loadData() {
        lifecycleScope.launch {
            try {
                val playlists = musicApi.getPlaylists()
                playlistAdapter.submitList(playlists)
                
                // 只设置第一首歌为当前歌曲，但不自动播放
                if (playlists.isNotEmpty()) {
                    val songs = playlists.map { pl ->
                        Song(
                            id = pl.id,
                            name = pl.name,
                            artist = pl.artist?.takeIf { it.isNotBlank() },
                            coverUrl = pl.coverUrl,
                            url = pl.url
                        )
                    }
                    (activity as? MainActivity)?.updateCurrentSong(songs[0], 0, songs)
                }
            } catch (e: Exception) {
                Log.e("PlaylistFragment", "加载失败", e)
                Toast.makeText(requireContext(), "加载失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun startMusicDetail(position: Int, songs: List<Song>) {
        (activity as? MainActivity)?.updateCurrentSong(songs[position], position, songs)
        startActivity(Intent(requireContext(), MusicDetailActivity::class.java).apply {
            putExtra("song_index", position)
            putExtra("songs", ArrayList(songs))
            addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
        })
    }
} 